import axios from 'axios';
import router from '../../router';

axios.defaults.timeout = 50000;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.baseURL = 'http://127.0.0.1:8080/gateway';

axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response)
        }
        return Promise.reject(response)
    },
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // Not Found
                case 404:
                    router.replace({
                        path: '/',
                        query: {
                            redirect: router.currentRoute.fullPath
                        }
                    });
                    break;
                case -1:
                    break
            }
            return Promise.reject(error)
        }
    }
);


export function getData(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            data: data,
            headers: {
                'content-type': 'application/json',
                'token': localStorage.token
            }
        })
            .then(response => {
                resolve(response.data)
            }).catch(error => {
            reject(error)
        })
    })
}

export function sendData(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data, {
            headers: {
                'content-type': 'application/json',
                'token': localStorage.token
            }
        }).then(response => {
            resolve(response.data)
        }).catch(error => {
            reject(error)
        })
    })
}

